//
//  MyTools.m
//  PersonalOC
//
//  Created by 韩琴 on 2018/8/21.
//  Copyright © 2018年 韩琴. All rights reserved.
//

#import "MyTools.h"
#import <AFNetworking/AFNetworking.h>

@implementation MyTools
/**
 谁作为window的rootvc vc:根控制器  isHaveNavBar：是否有navbar
 */
+ (void)changeRootVc:(UIViewController *)vc and:(BOOL)isHaveNavBar
{
    if(isHaveNavBar)
    {
        BaseNavigationController *nav =[[BaseNavigationController alloc] initWithRootViewController:vc];
        [UIApplication sharedApplication].delegate.window.rootViewController = nav;
    }
    else
    {
        [UIApplication sharedApplication].delegate.window.rootViewController = vc;
        
    }
    
}
/**
 POST请求
 
 @param url 接口地址
 @param dict 参数
 @param scrollView 列表或者滚动视图
 @param view 菊花所在view
 @param success 成功回调
 @param failure 失败回调
 */
+ (void)PostNetworkWithUrl:(NSString *)url withDict:(NSDictionary *)dict withScrollView:(UIScrollView *)scrollView withInView:(UIView *)view success:(PPHttpRequestSuccess)success
                   failure:(PPHttpRequestFailed)failure
{
    //收回键盘
    [[LYTools getCurrentVC].view endEditing:YES];
    
    //如果正在上下拉刷新 就不显示
    if([scrollView.mj_header isRefreshing]==NO&&[scrollView.mj_footer isRefreshing]==NO)
    {
        if(view!=nil)
        {
            [MBProgressHUD showHUDAddedTo:view animated:YES];
        }
    }
    
    //参数部分
    NSMutableDictionary *muDict = [NSMutableDictionary dictionary];
    
    if(dict!=nil)
    {
        [muDict setDictionary:dict];
        
    }
    //添加固定参数Token
    if(_userModel.token!=nil)
    {
        [LYNetworkManager setValue:_userModel.token forHTTPHeaderField:@"access-token"];
    }
    //地址部分
    NSString *allUrl = [NSString stringWithFormat:@"%@/%@",_addressUrl,url];
    
    //判断视图是否需要加无数据状态
    if(scrollView!=nil)
    {
        //免得第一次获取数据数据还未出来就展示
        //        [scrollView ly_startLoading];
        scrollView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"暂无数据"
                                                            titleStr:@"暂无数据"
                                                           detailStr:@""];
        
    }
    //发起网络请求
    [LYNetworkManager POST:allUrl parameters:muDict success:^(id responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            //打印接口地址和参数 和返回的参数
            DLog(@"\n接口调用成功___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl,url,muDict,responseObject);
            
            
//            //给视图加上没有数据时的缺省页
//            if(scrollView!=nil)
//            {
//
//                //                scrollView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"缺省页-无数据"
//                //                                                                    titleStr:@"暂无数据"
//                //                                                                   detailStr:@""];
//            }
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [scrollView.mj_header endRefreshing];
            
            [scrollView.mj_footer endRefreshing];
            
            BaseModel *dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
            
            if (![dataModel.code isEqualToString:@"rest.success"]) {
                
                if(![MyTools stringIsNil:dataModel.message])
                {
                    [MyTools showMessage:dataModel.message];
                }
                else if(![MyTools stringIsNil:dataModel.desc])
                {
                    [MyTools showMessage:dataModel.desc];
                }
                else
                {
                    [MyTools showMessage:@"操作失败"];
                }
                
                return ;
            }
            
            if(success!=nil)
            {
                
                success(dataModel.result);
            }
            
            
            
            
        });
        
    } failure:^(NSError *error) {
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
//            //给视图加上没有数据时的缺省页
//            if(scrollView!=nil)
//            {
//
//                //                scrollView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"缺省页-无数据"
//                //                                                                    titleStr:@"暂无数据"
//                //                                                                   detailStr:@""];
//            }
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [scrollView.mj_header endRefreshing];
            
            [scrollView.mj_footer endRefreshing];
            
            //打印接口地址和参数 和返回的参数
            DLog(@"\n报错___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的失败原因%@",_addressUrl,url,muDict,error);
            
            [MyTools showMessage:@"网络连接失败"];
            
            if(failure!=nil)
            {
                failure(error);
            }
            
        });
        
    }];
    
    
}
/**
 GET请求
 
 @param url 接口地址
 @param dict 参数
 @param scrollView 列表或者滚动视图
 @param view 菊花所在view
 @param success 成功回调
 @param failure 失败回调
 */
+ (void)GetNetworkWithUrl:(NSString *)url withDict:(NSDictionary *)dict withScrollView:(UIScrollView *)scrollView withInView:(UIView *)view success:(PPHttpRequestSuccess)success
                  failure:(PPHttpRequestFailed)failure
{
    //如果正在上下拉刷新 就不显示
    if([scrollView.mj_header isRefreshing]==NO&&[scrollView.mj_footer isRefreshing]==NO)
    {
        
        if(view!=nil)
        {
            
            [MBProgressHUD showHUDAddedTo:view animated:YES];
        }
    }
    
    NSMutableDictionary *muDict = [NSMutableDictionary dictionary];
    
    //添加参数
    if(dict!=nil)
    {
        [muDict setDictionary:dict];
    }
    
    NSString *allUrl = [NSString stringWithFormat:@"%@/%@",_addressUrl,url];
    
    //判断视图是否需要加无数据状态
    
    if(scrollView!=nil)
    {
//        //免得第一次获取数据数据还未出来就展示
//        [scrollView ly_startLoading];
        scrollView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"暂无数据"
                                                            titleStr:@"暂无数据"
                                                           detailStr:@""];
        
    }
    
    
    
    [LYNetworkManager GET:allUrl parameters:muDict success:^(id responseObject) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
//            //给视图加上没有数据时的缺省页
//            if(scrollView!=nil)
//            {
//
//                scrollView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"缺省页-无数据"
//                                                                    titleStr:@"暂无数据"
//                                                                   detailStr:@""];
//            }
            
            
            //打印接口地址和参数 和返回的参数
            DLog(@"\n接口调用成功___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl,url,muDict,responseObject);
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [scrollView.mj_header endRefreshing];
            
            [scrollView.mj_footer endRefreshing];
            
            BaseModel *dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
            
            if (![dataModel.state isEqualToString:@"200"]) {
                
                
                [MyTools showMessage:dataModel.message];
                
                return ;
            }
            
            if(success!=nil)
            {
                
                success(dataModel.data);
            }
            
            
            
            
        });
        
    } failure:^(NSError *error) {
        
        
        
//        //给视图加上没有数据时的缺省页
//        if(scrollView!=nil)
//        {
//
//            scrollView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"缺省页-无数据"
//                                                                titleStr:@"暂无数据"
//                                                               detailStr:@""];
//        }
//
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [scrollView.mj_header endRefreshing];
            
            [scrollView.mj_footer endRefreshing];
            
            //打印接口地址和参数 和返回的参数
            DLog(@"\n报错___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的失败原因%@",_addressUrl,url,muDict,error);
            
            [MyTools showMessage:@"网络连接失败"];
            
            if(failure!=nil)
            {
                failure(error);
            }
            
        });
        
    }];
    
    
}

/**
 上传文件
 
 @param url url地址
 @param dict 参数
 @param view 展示菊花的view 不传就是window
 @param name 对应在服务器上面的名字
 @param filePath 文件路径
 @param success 成功
 @param failure 失败
 */
+ (void)UploadNetworkWithUrl:(NSString *)url withDict:(NSDictionary *)dict  withInView:(UIView *)view withFileName:(NSString *)name withFilePath:(NSString *)filePath success:(PPHttpRequestSuccess)success
                     failure:(PPHttpRequestFailed)failure{
    
    
    if(view==nil)
    {
        
        view = [UIApplication sharedApplication].keyWindow;
    }
    
    MBProgressHUD *hud =  [MBProgressHUD showHUDAddedTo:view animated:YES];
    
    NSMutableDictionary *muDict = [NSMutableDictionary dictionary];
    
    //添加参数
    if(dict!=nil)
    {
        [muDict setDictionary:dict];
    }
    NSString *allUrl = [NSString stringWithFormat:@"%@/%@",_addressUrl,url];
    [LYNetworkManager uploadFileWithURL:allUrl parameters:muDict name:name filePath:filePath progress:^(NSProgress *progress) {
        
        hud.label.text = [NSString stringWithFormat:@"上传进度:%.2f",progress.fractionCompleted*100];
        
    } success:^(id responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"\n接口调用成功___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl,url,muDict,responseObject);
            
            [hud hideAnimated:YES];
            
            
            BaseModel *dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
            
            if (![dataModel.code isEqualToString:@"rest.success"]) {
                
                [MyTools showMessage:dataModel.message];
                
                return ;
            }
            
            if(success!=nil)
            {
                
                success(dataModel.result);
            }
        });
        
        
    } failure:^(NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:view animated:YES];
            
            [hud hideAnimated:YES];
            
            //打印接口地址和参数 和返回的参数
            NSLog(@"\n报错___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的失败原因%@",_addressUrl,url,muDict,error);
            
            [MyTools showMessage:@"网络连接失败"];
            
            if(failure!=nil)
            {
                failure(error);
            }
            
        });
    }];
    
}





/**
 上传多个图片
 
 @param url 接口
 @param dict 参数
 @param fileArr 传到服务端的参数名(不是文件名)
 @param imgArr 图片数组
 @param view 展示菊花的view
 @param success 成功
 @param failure 失败
 */
+ (void)uploadMoreImageWithURL:(NSString *)url withDict:(NSDictionary *)dict withFileArr:(NSArray *)fileArr withImageArr:(NSArray *)imgArr  withInView:(UIView *)view success:(PPHttpRequestSuccess)success   failure:(PPHttpRequestFailed)failure{
    {
        
        
        if(view==nil)
        {
            
            view = [UIApplication sharedApplication].keyWindow;
        }
        
        MBProgressHUD *hud =  [MBProgressHUD showHUDAddedTo:view animated:YES];
        
        
        NSString *allUrl = [NSString stringWithFormat:@"%@/%@",_addressUrl,url];
        
        
        NSMutableDictionary *muDict = [NSMutableDictionary dictionary];
        
        //添加固定参数
        if(dict!=nil)
        {
            [muDict setDictionary:dict];
        }
        
        
        
        
        [LYNetworkManager setAFHTTPSessionManagerProperty:^(AFHTTPSessionManager *sessionManager) {
            
            
            
            
            
            [sessionManager POST:allUrl parameters:muDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                
                for (NSUInteger i = 0; i < imgArr.count; i++) {
                    // 图片经过等比压缩后得到的二进制文件
                    NSData *imageData = UIImageJPEGRepresentation(imgArr[i], 0.f);
                    // 默认图片的文件名, 若fileNames为nil就使用
                    
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"yyyyMMddHHmmss";
                    NSString *str = [formatter stringFromDate:[NSDate date]];
                    NSString *imageFileName = [NSString stringWithFormat:@"%@%ld.%@",str,i,@"png"];
                    
                    NSString *imageType = @"png";
                    
                    [formData appendPartWithFileData:imageData name:fileArr[i] fileName:imageFileName mimeType:imageType];
                }
                
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                //上传进度
                dispatch_sync(dispatch_get_main_queue(), ^{
                    
                    
                    hud.label.text = [NSString stringWithFormat:@"上传图片进度:%.2f",uploadProgress.fractionCompleted*100];
                });
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSLog(@"\n接口调用成功___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的参数%@",_addressUrl,url,muDict,responseObject);
                    
                    [hud hideAnimated:YES];
                    
                    
                    BaseModel *dataModel = [BaseModel mj_objectWithKeyValues:responseObject];
                    
                    if (![dataModel.code isEqualToString:@"rest.success"]) {
                        
                        
                        [MyTools showMessage:dataModel.message];
                        
                        return ;
                    }
                    
                    if(success!=nil)
                    {
                        
                        success(dataModel.result);
                    }
                });
                
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [MBProgressHUD hideHUDForView:view animated:YES];
                    
                    [hud hideAnimated:YES];
                    
                    //打印接口地址和参数 和返回的参数
                    NSLog(@"\n报错___\n根地址___%@\n接口:%@ \n参数:%@  \n返回的失败原因%@",_addressUrl,url,muDict,error);
                    
                    [MyTools showMessage:@"网络连接失败"];
                    
                    if(failure!=nil)
                    {
                        failure(error);
                    }
                    
                });
                
            }];
            
            
            
        }];
        
    }
    
}
#pragma mark——————————————————微信支付
+ (void)wechtPay_partnerId:(NSString *)partnerId prepayId:(NSString *)prepayId package:(NSString *)package nonceStr:(NSString *)nonceStr timeStamp:(UInt32 )timeStamp sign:(NSString *)sign appid:(NSString *)appid{
    
    [WXApi registerApp:appid];
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = partnerId;
    request.prepayId= prepayId;
    request.package = package;
    request.nonceStr= nonceStr;
    request.timeStamp= timeStamp;
    request.sign= sign;
    [WXApi sendReq:request];
}


#pragma mark——————————支付宝
/*
 orderString : 后台返回的密钥串
 successBlock: 成功回调
 wrongBlock  : 失败回调
 */

+ (void)aliPay:(NSString *)orderString withSuccessResult:(payBlock)successBlock withWrongResult:(payBlock)wrongBlock
{
    
    
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:@"wodezhifubao" callback:^(NSDictionary *resultDic) {
        NSString *message = @"";
        switch([[resultDic objectForKey:@"resultStatus"] integerValue])
        {
            case 9000:message = @"订单支付成功";break;
            case 8000:message = @"正在处理中";break;
            case 4000:message = @"订单支付失败";break;
            case 6001:message = @"用户中途取消";break;
            case 6002:message = @"网络连接错误";break;
            default:message = @"未知错误";
        }
        //支付成功
        if([[resultDic objectForKey:@"resultStatus"] integerValue]==9000)
        {
            NSLog(@"支付成功");
            
            if(successBlock!=nil)
            {
                successBlock();
            }
            
        }
        else
        {
            
            [LYTools showMessage:message];
            
            if(wrongBlock!=nil)
            {
                wrongBlock();
            }
        }
        
    }];
}

#pragma mark——————————————————第三方登录
+ (void)UMLogin:(UMSocialPlatformType)platformType withOpenIDBlock:(void(^)(UMSocialUserInfoResponse *value)) block
{
    
    UIViewController *vc = [LYTools getCurrentVC];
    
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:vc completion:^(id result, NSError *error) {
        
        UMSocialUserInfoResponse *resp = result;
        
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        DLog(@" uid: %@", resp.uid);
        DLog(@" openid: %@", resp.openid);
        DLog(@" accessToken: %@", resp.accessToken);
        DLog(@" refreshToken: %@", resp.refreshToken);
        DLog(@" expiration: %@", resp.expiration);
        
        // 用户数据
        DLog(@" name: %@", resp.name);
        DLog(@" iconurl: %@", resp.iconurl);
        DLog(@" gender: %@", resp.unionGender);
        
        // 第三方平台SDK原始数据
        DLog(@" originalResponse: %@", resp.originalResponse);
        
        if(block!=nil)
        {
            block(resp);
        }
    }];
}
#pragma mark————————————————————友盟分享
/**
 *  友盟分享
 *
 *  @param shareUrl 分享链接地址(点击)
 *  @param vc       当前vc
 *  @param title    标题
 *  @param image    分享图片
 *  @param Source   描述
 */
+ (void)UMShareWithShareUrl:(NSString *)shareUrl  withViewController:(UIViewController *)vc  withTitle:(NSString *)title  withImage:(UIImage *)image withSource:(NSString *)Source{
    
    
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //设置文本
    messageObject.text = title;
    
    if(image==nil)
    {
        image = [UIImage imageNamed:@"图片-2"];
    }
    
    UMShareWebpageObject *umObj = [UMShareWebpageObject shareObjectWithTitle:title descr:Source thumImage:image];
    umObj.webpageUrl  = shareUrl;
    
    messageObject.shareObject = umObj;
    
    
    
    //弹出界面
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone),@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        
        
        
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:vc completion:^(id result, NSError *error) {
            
            
            
        }];
        
    }];}
@end
